import Http from '../../../utils/http';
const http = new Http();
import {Toast} from 'antd-mobile-rn';
import { TYPES } from '../reduces/orderRenduces';
import { i18n } from '../../../i18n';

export function loadOrders(status = 1){
    return (dispatch,getState)=>{
        let {order} = getState();
        if(order.loading){
            return;
        }
        dispatch(loadingAction(true))
        http.post("order/index",{
            page:order.openpage,
            status:status
        })
        .then((res)=>{
            dispatch(loadingAction(false))
            if(res.status){
                let orders = res.data.orders;
                let orderKeys = Object.keys(orders);
                let list = [];
                let {openOrders,closeOrders,closepage,openpage} = order;
                if(status == 1){
                    list = order.openOrders;
                    openpage += 1;
                }else{
                    list = order.closeOrders;
                    closepage += 1;
                }
                if(orderKeys.length == 0){
                    //TODO 显示没有更多数据
                }else{
                    for(let time of orderKeys){
                        let isAppend = true;
                        for(let item of list){
                            if(item.time == time){
                                item.data = item.data.concat(orders[time]);
                                isAppend = false;
                            }
                        }
                        isAppend && list.push({
                            title:new Date(Number(time)).FormatDate("yyyy-MM-dd"),
                            time:time,
                            data:orders[time]
                        })
                    }
                    dispatch({
                        type:TYPES.LOADORDER,
                        openOrders,
                        closeOrders,
                        openpage:openpage,
                        closepage:closepage
                    })
                }
            }else{
                toast(i18n.t(res.message));
            }
        })
        .catch((e)=>{
            console.log(e);
            dispatch(loadingAction(false))
            toast(i18n.t("net.neterror"))
        })
    }
}

function loadingAction(loading = false){
    return {
        type:TYPES.CHANGELOADING,
        loading
    }
}

function toast(msg = ""){
    Toast.info(msg,3,null,false);
}